﻿#region Copyright

// All Material Copyright © 2010 Dynamic Concepts Development Corp., All Rights Reserved.
//      Portions Copyright © 1984-2009 Dynamic Concepts Development Corp., All Rights Reserved.
// For further information please contact: SoftwareSupport@dynconcepts.com
// Dynamic Concepts Development Corp.  311 W 57th St. Suite #422, New York, NY 10019

#endregion

#region Using References

using System.ComponentModel;
using System.Windows;
using System.Windows.Threading;

#endregion

namespace DynConDevCorp.OpenArch.DynAppFramework.Tiers.UserInterface.WPF.Engine
{
    public abstract class ViewModelItemBase : DependencyObject, INotifyPropertyChanged
    {
        #region Constructors

        protected ViewModelItemBase()
        {
            r_CreationDispatcher = Dispatcher;
        }

        #endregion

        #region Public Properies and Indexers

        public Dispatcher CreationDispatcher
        {
            get { return r_CreationDispatcher; }
        }

        #endregion

        #region Public Methods

        public bool InvokeRequired()
        {
            return !r_CreationDispatcher.CheckAccess();
        }

        #endregion

        #region Public Events

        public virtual event PropertyChangedEventHandler PropertyChanged;

        #endregion

        #region Protected Methods

        protected T GetValue<T>(DependencyProperty property)
        {
            if (InvokeRequired())
            {
                DispatcherOperation operation = r_CreationDispatcher.BeginInvoke(new GetValueDelegate<T>(GetValue<T>), new object[] {property});
                operation.Wait();
                T retVal = (T) operation.Result;
                return retVal;
            }
            return (T) GetValue(property);
        }

        protected void NotifyPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler shadow = PropertyChanged;
            if (shadow != null)
                shadow(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion

        #region Instance Fields (ReadOnly)

        private readonly Dispatcher r_CreationDispatcher;

        #endregion

        #region Nested type: GetValueDelegate

        private delegate T GetValueDelegate<T>(DependencyProperty property);

        #endregion
    }
}